package com.witdata.security.auth;

import com.alibaba.fastjson2.JSON;
import com.witdata.common.domain.Result;
import com.witdata.common.domain.Status;
import com.witdata.security.exception.MyAccessDeniedException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(authException.getClass() == BadCredentialsException.class){
            out.write(JSON.toJSONString(Result.ok(Status.PASSWORDERROR)));
        } else if(authException.getClass() == InsufficientAuthenticationException.class){
            out.write(JSON.toJSONString(Result.ok(Status.USERPERMDEFICIENCY)));
            log.error("对于来自{}的请求{},返回{}--->{}", request.getLocalAddr(), request.getRequestURI(), Status.USERPERMDEFICIENCY.getCode(), Status.USERPERMDEFICIENCY.getMsg());
        } else if(authException.getClass() == MyAccessDeniedException.class){
            out.write(JSON.toJSONString(Result.ok(((MyAccessDeniedException) authException).getStatus())));
        }
        out.flush();
        out.close();
    }
}
